package com.intct.hbase.ddl.table;

import com.intct.hbase.ddl.namespace.AbsNamespace;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author gufg
 * @since 2025-07-10 15:43
 * 命名空间名称
 * 表名称
 * 列族
 * 版本
 *
 */
public class Alter extends AbsNamespace {

    /*
        命名空间名称
     */
    private String namespace;

    /*
        声明表名
     */
    private String tableName;

    /*
    多列族多版本
     */
    private Map<String, Integer> familyMap = new HashMap<>();

    public Alter(String namespace, String tableName, Map<String, Integer> familyMap) {
        this.namespace = namespace;
        this.tableName = tableName;
        this.familyMap = familyMap;
    }

    @Override
    public void execCommand(Admin admin) throws IOException {
        // alter 'ns:t1',{NAME => 'f1', VERSIONS =>3}
        TableName hbaseTableName = TableName.valueOf(namespace, tableName);
        // 判断表存在，则修改
        if (admin.tableExists(hbaseTableName)) {
            // 原表描述
            TableDescriptor oldDescriptor = admin.getDescriptor(hbaseTableName);

            // 创建表描述
            TableDescriptorBuilder tableDescriptorBuilder = TableDescriptorBuilder.newBuilder(oldDescriptor);

            // 增加列族
//            ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder = ColumnFamilyDescriptorBuilder.newBuilder("f1".getBytes());
//            columnFamilyDescriptorBuilder.setMaxVersions(3);
//            tableDescriptorBuilder.setColumnFamily(columnFamilyDescriptorBuilder.build());

            // 删除列族
//            tableDescriptorBuilder.removeColumnFamily("f4".getBytes());

            // 修改列族 版本由3改为5
            List<ColumnFamilyDescriptor> columnFamilyDescriptors = Arrays.asList(oldDescriptor.getColumnFamilies());
            ColumnFamilyDescriptor oldDescriptorColumnFamily = oldDescriptor.getColumnFamily("f1".getBytes());

            if (oldDescriptorColumnFamily != null) {
//            if (columnFamilyDescriptors.contains("f1")) {
                ColumnFamilyDescriptorBuilder columnFamilyDescriptorBuilder =
                        ColumnFamilyDescriptorBuilder.newBuilder(oldDescriptor.getColumnFamily("f1".getBytes()));

                columnFamilyDescriptorBuilder.setMaxVersions(5);

                tableDescriptorBuilder.modifyColumnFamily(columnFamilyDescriptorBuilder.build());
            } else {
                System.out.println("列族信息不存！");
            }

            // 修改表
            admin.modifyTable(tableDescriptorBuilder.build());

        }
    }

    public static void main(String[] args) throws IOException {
        new Alter("intct82", "t03", null).start();
    }
}
